// +----------------------------------------------------------------------
// | Thinkstars
// +----------------------------------------------------------------------
// | 版权所有 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 星辰工作室
// +----------------------------------------------------------------------
jQuery(document).ready(function() {

    // 文件上传集合
    var webuploader = [];
    // 当前上传对象
    var curr_uploader = {};
    // wangeditor编辑器集合
    var wangeditors = {};
    // 当前图标选择器
    var curr_icon_picker;
    var layer_icon;

    // 打开图标选择器
    $('.js-icon-picker').click(function() {
        curr_icon_picker = $(this);
        var icon_input = curr_icon_picker.find('.icon_input');
        if (icon_input.is(':disabled')) {
            return;
        }
        layer_icon = layer.open({
            type: 1,
            title: '图标选择器',
            area: ['90%', '90%'],
            scrollbar: false,
            content: $('#icon_tab')
        });
    });

    // 选择图标
    $('.js-icon-content div').on('click', function(event) {
        var icon = $(this).find('i').attr('class');
        curr_icon_picker.find('.input-group-addon.icon').html('<i class="' + icon + '"></i>');
        curr_icon_picker.find('.icon_input').val(icon);
        layer.close(layer_icon);
    });

    // 清空图标
    $('.delete-icon').click(function(event) {
        event.stopPropagation();
        if ($(this).prev().is(':disabled')) {
            return;
        }
        $(this).prev().val('');
        $(this).prev().prev().html('<i class="fa fa-fw fa-plus-circle"></i>');
    });

    // 联动下拉框
    $('.select-linkage').change(function() {
        var self = $(this), // 下拉框
            value = self.val(), // 下拉框选中值
            ajax_url = self.data('url'), // 异步请求地址
            param = self.data('param'), // 参数名称
            next_items = self.data('next-items').split(','), // 下级下拉框的表单名数组
            next_item = next_items[0]; // 下一级下拉框表单名

        // 下级联动菜单恢复默认
        if (next_items.length > 0) {
            for (var i = 0; i < next_items.length; i++) {
                $('select[name="' + next_items[i] + '"]').html('<option value="">请选择：</option>');
            }
        }

        if (value != '') {
            Stars.loading();
            // 获取数据
            $.ajax({
                    url: ajax_url,
                    type: 'POST',
                    dataType: 'json',
                    data: param + "=" + value
                })
                .done(function(res) {
                    Stars.loading('hide');
                    if (res.code == '1') {
                        var list = res.list;
                        if (list) {
                            for (var item in list) {
                                var option = $('<option></option>');
                                option.val(list[item].key).html(list[item].value);
                                $('select[name="' + next_item + '"]').append(option);
                            }
                        }
                    } else {
                        Stars.notify(res.msg, 'danger');
                    }
                })
                .fail(function(res) {
                    Stars.loading('hide');
                    Stars.notify($(res.responseText).find('h1').text() || '数据请求失败~', 'danger');
                });
        }
    });

    // 多级联动下拉框
    $('.select-linkages').change(function() {
        var self = $(this), // 下拉框
            value = self.val(), // 下拉框选中值
            token = self.data('token'), // token
            pidkey = self.data('pidkey') || 'pid',
            next_level = self.data('next-level'), // 下一级别
            next_level_id = self.data('next-level-id') || ''; // 下一级别的下拉框id

        // 下级联动菜单恢复默认
        if (next_level_id != '') {
            $('#' + next_level_id).html('<option value="">请选择：</option>');
            var has_next_level = $('#' + next_level_id).data('next-level-id');
            if (has_next_level) {
                $('#' + has_next_level).html('<option value="">请选择：</option>');
                has_next_level = $('#' + has_next_level).data('next-level-id');
                if (has_next_level) {
                    $('#' + has_next_level).html('<option value="">请选择：</option>');
                }
            }
        }

        if (value != '') {
            Stars.loading();
            // 获取数据
            $.ajax({
                    url: lwwan.get_level_data,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        token: token,
                        level: next_level,
                        pid: value,
                        pidkey: pidkey
                    }
                })
                .done(function(res) {
                    Stars.loading('hide');
                    if (res.code == '1') {
                        var list = res.list;
                        if (list) {
                            for (var item in list) {
                                var option = $('<option></option>');
                                option.val(list[item].key).text(list[item].value);
                                $('#' + next_level_id).append(option);
                            }
                        }
                    } else {
                        Stars.loading('hide');
                        Stars.notify(res.msg, 'danger');
                    }
                })
                .fail(function(res) {
                    Stars.loading('hide');
                    Stars.notify($(res.responseText).find('h1').text() || '数据请求失败~', 'danger');
                });
        }
    });

    // 排序
    $('.nestable').each(function() {
        $(this).nestable({ maxDepth: 1 }).on('change', function() {
            var $items = $(this).nestable('serialize');
            var name = $(this).data('name');
            var value = [];
            for (var item in $items) {
                value.push($items[item].id);
            }
            if (value.length) {
                $('input[name=' + name + ']').val(value.join(','));
            }
        });
    });

    // 日期
    $('.js-date').each(function() {
        laydate.render({
            elem: this,
            trigger: 'click'
        });
    });

    // 日期时间
    $('.js-time').each(function() {
        laydate.render({
            elem: this,
            type: 'time',
            trigger: 'click'
        });
    });

    // 日期时间范围
    $('.js-date-range').each(function() {
        var data = {
            elem: this,
            type: 'datetime',
            range: true,
            trigger: 'click',
            quickConfirm: true, // 是否选择之后快速确定
            quickSelect: [
                'today', // 这个是个内部的支持的，可以简化设置
                'lastDays-7', // 过去7天
                'lastDays-30', // 过去30天
                'yesterday', // 昨天
                'lastMonth', // 上个月
                'thisMonth', // 这个月
                {
                    title: '今年',
                    value: function() {
                        var date1 = new Date();
                        var date2 = new Date();
                        console.log()
                        date1.setYear(date1.getFullYear());
                        date1.setMonth('0');
                        date1.setDate(1);
                        date1.setHours(0, 0, 0, 0);
                        date2.setDate(date2.getDate() + 1);
                        date2.setHours(0, 0, 0, 0);
                        return [date1, date2];
                    }
                }
            ],
            done: function(value, date, endDate) {
                var hours = endDate.hours;
                var minutes = endDate.minutes;
                var seconds = endDate.seconds;
                if (hours == "0" && minutes == "0" && seconds == "0") {
                    $(".layui-laydate-footer [lay-type='datetime'].laydate-btns-time").click();
                    // 改变结束时间默认值
                    $(".laydate-main-list-1 .layui-laydate-content li ol li:last-child").click();
                    $(".layui-laydate-footer [lay-type='date'].laydate-btns-time").click();
                }
            }
        }
        var isEnd = $(this).attr('endToday');
        if (isEnd != undefined) {
            var today = `${new Date().getFullYear()}-${new Date().getMonth()+1}-${new Date().getDate()}`;
            data.max = today;
        }
        laydate.render(data);
    });

    // jquerydaterangepicker日期选择
    $(function() {
        let initDateStr = $('.js-daterangepicker').val();
        let initDate = '';
        if (initDateStr) {
            initDate = initDateStr.split(' - ');
        }

        var locale = {
            "format": 'YYYY-MM-DD',
            "separator": " - ",
            "applyLabel": "确定",
            "cancelLabel": "取消",
            "fromLabel": "起始时间",
            "toLabel": "结束时间'",
            "customRangeLabel": "自定义",
            "weekLabel": "W",
            "daysOfWeek": ["日", "一", "二", "三", "四", "五", "六"],
            "monthNames": ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            "firstDay": 1
        };
        $('.js-daterangepicker').daterangepicker({
            'locale': locale,
            ranges: {
                '今日': [moment(), moment()],
                '昨日': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                '最近7日': [moment().subtract(6, 'days'), moment()],
                '最近30日': [moment().subtract(29, 'days'), moment()],
                '本月': [moment().startOf('month'), moment().endOf('month')],
                '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month')
                    .endOf('month')
                ]
            },
            "alwaysShowCalendars": true,
            "startDate": initDate[0] || new Date(),
            "endDate": initDate[1] || new Date(),
            "opens": "right",
        }, function(start, end, label) {
            console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
        });
    });

    // wangeditor编辑器
    $('.js-wangeditor').each(function() {
        var wangeditor_name = '#' + $(this).attr('name');
        var imgExt = $(this).data('img-ext') || '';
        // 实例化编辑器
        wangeditors[wangeditor_name] = new wangEditor(wangeditor_name);
        wangeditors[wangeditor_name].config.printLog = false;
        //粘贴过滤格式
        //wangeditors[wangeditor_name].config.pasteFilterStyle = true
            //忽略图片
        wangeditors[wangeditor_name].config.pasteIgnoreImg = true
            //自定义处理粘贴的文本内容,content 即粘贴过来的内容（html 或 纯文本），可进行自定义处理然后返回
		/**
        wangeditors[wangeditor_name].config.pasteTextHandle = function(content) {
            //console.log(content)
            if (content == '' && !content) return ''
            var str = unescape(content)
            str = str.replace(/<xml>[\s\S]*?<\/xml>/ig, '')
            str = str.replace(/<style>[\s\S]*?<\/style>/ig, '')
            str = str.replace(/<\/?[^>]*>/g, '')
            str = str.replace(/[ | ]*\n/g, '\n')
            str = str.replace(/[ | ]*\r/g, '\r')
            str = str.replace(/&nbsp;/ig, "")
                //console.log(str)		  
            return str
        }
		**/
        // 上传图片地址
        wangeditors[wangeditor_name].config.uploadImgServer = lwwan.image_upload_url + '?from=wangeditor';
        // 允许上传图片后缀
        wangeditors[wangeditor_name].config.imgExt = imgExt;
        $text1 = $(wangeditor_name.slice(0, -1));
        wangeditors[wangeditor_name].config.onchange = function(html) {
                $text2 = $(wangeditor_name.slice(0, -1));
                $text2.val(html)
            }
            // 上传视频 
        wangeditors[wangeditor_name].config.uploadVideoServer = '/api/v1/607806de9b4d2'
        wangeditors[wangeditor_name].config.uploadVideoParamsWithUrl = true
            // 配置文件名
        wangeditors[wangeditor_name].config.uploadFileName = 'file';
        wangeditors[wangeditor_name].config.uploadVideoName = 'file'
        wangeditors[wangeditor_name].create();
        $text1.val(wangeditors[wangeditor_name].txt.html());
    });
    
    $(".js-selectajax").each(function(){
        var url = $(this).data("url");
        if(!url){
            url = "/admin.php/admin/ajax/searchUser";
        }
        $(this).select2({
                placeholder:  '请输入',
                language:"zh-CN",
                ajax: {
                    url: url,
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                        return {
                            key: params.term, // search term
                            page: params.page
                        };
                    },
                    processResults: function (data, params) {
                        params.page = params.page || 1;

                        return {
                            results: data.results,
                           /* pagination: {
                                more: (params.page * 10) < 110//data.total_count
                            }*/
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 1,
                //templateResult: formatRepoProvince, // omitted for brevity, see the source of this page
                //templateSelection: formatRepoProvince // omitted for brevity, see the source of this page
        });
        
    });
    
    
     //地图选点输入组件
    $(".js-map-address").each(function(i,e){
         //定义回传事件
         window['selectLoctionClickCall'+i] = function(data){
             $(e).find('.map-levels').val(data.province + ',' + data.city + ',' + data.district);
             $(e).find('.map-province').val(data.province);
             $(e).find('.map-city').val(data.city);
             $(e).find('.map-district').val(data.district);
             $(e).find('.map-address').val(data.address);
             $(e).find('.map-lng').val(data.lng);
             $(e).find('.map-lat').val(data.lat);
             console.log("收到回调",data);             
         };
         $(e).find(".map-btn").click(function(){
               var url = "/admin.php/admin/map/map?callback=selectLoctionClickCall" + i; 
               layer.open({
                    type:2,
                    title:"点击选择位置",
                    area:['1000px','680px'],                 
                    content:url,
               });
               return;  
         });
    })
    
     //省市区输入组件
    $(".js-address").each(function(i,e){         
         //定义回传事件
         window['selectAddressClickCall'+i] = function(data){
             $(e).find('.map-levels').val(data.province + ',' + data.city + ',' + data.district);
             $(e).find('.map-province').val(data.province);
             $(e).find('.map-province_id').val(data.province_id);          
             $(e).find('.map-city').val(data.city);
             $(e).find('.map-city_id').val(data.city_id);             
             $(e).find('.map-district').val(data.district);    
             $(e).find('.map-district_id').val(data.district_id);             
             $(e).find('.map-lng').val(data.lng);
             $(e).find('.map-lat').val(data.lat);
             console.log("收到回调",data);             
         };
         $(e).find(".map-btn").click(function(){
               var url = "/admin.php/admin/map/address?callback=selectAddressClickCall" + i; 
               layer.open({
                    type:2,
                    title:"点击选择地区",
                    area:['1000px','350px'],                 
                    content:url,
               });
               return;  
         });
    })
    
      //手机号输入组件
    $(".js-mobile").each(function(i,e){
        var url = $(e).data("url");   
        var scene = $(e).data("scene");           
        if(!url){
            url = "/admin.php/admin/ajax/get_mobile_prefix?scene="+scene;
        }
        var prefix = "86";
        var mobile = "";        
        var old_mobile = $(e).find(".mobile-self").val();
        if(old_mobile ){
            if(/\-/.test(old_mobile)){                
                var arr = old_mobile.split("-");
                prefix = arr[0];
                mobile = arr[1];                
            }else{
                mobile = old_mobile;
            }            
        }      
        $(e).find(".mobile-prefix").val(prefix).trigger('change');
        $(e).find(".mobile-end").val(mobile);         
        $.post(url,function(result){
            var i ;
            for(i in result.results){
                var line = result.results[i];
                $(e).find(".mobile-prefix").append('<option value="'+ line.id +'">'+ line.text +'</option>');                
            }               
            $(e).find(".mobile-prefix").val(prefix).trigger('change');                        
        });
        $(e).find(".mobile-prefix").change(function(){         
             prefix = $(this).val();
             if(mobile){
                $(e).find(".mobile-self").val(prefix + '-' + mobile);
             }else{
                $(e).find(".mobile-self").val("");
             }           
        });
        $(e).find(".mobile-end").keyup(function(){
             mobile = $(this).val();
             if(mobile){
                $(e).find(".mobile-self").val(prefix + '-' + mobile);
             }else{
                $(e).find(".mobile-self").val("");
             }
        });      
    })
    
    //已经存在的图片增加删除事件
    $('.js-upload,.js-uploads').each(function() {
        var $input_file = $(this).find('input');
        var $input_file_name = $input_file.attr('name');
        // 是否多图片上传
        var $multiple = $input_file.data('multiple');
        // 图片列表
        var $file_list = $('#file_list_' + $input_file_name);
        // 删除图片
        $file_list.delegate('.remove-picture', 'click', function() {
            $(this).closest('.file-item').remove();
            if ($multiple) {
                var ids = [];
                $file_list.find('.remove-picture').each(function() {
                    ids.push($(this).data('id'));
                });
                $input_file.val(ids.join(','));
            } else {
                $input_file.val('');
            }
            Stars.iview();
        });
    });
    $('.js-upload-image-atlas').click(function() {
        input_name = $(this).attr('data-name');
        layer.open({
            type: 2,
            shade:0.3,
            title: '图册管理',
            area: ['70%', '60%'],
            scrollbar: false,
            content: ['/admin.php/admin/upload/atlas?type=1&input_name='+input_name]
        });
    });
    $('.js-upload-images-atlas').click(function() {
        input_name = $(this).attr('data-name');
        layer.open({
            type: 2,
            shade:0.3,
            title: '图册管理',
            area: ['70%', '60%'],
            scrollbar: false,
            content: ['/admin.php/admin/upload/atlas?type=2&input_name='+input_name]
        });
    });
    // 图集幻灯片
    Stars.iview();

    $('#typeid').on('change', () => {
        $.post('/admin.php/operation/ads_type/getSize', { "id": $("#typeid").val() })
            .then(res => {
                if (res.code == 1) {
                    cutPicWidth = res.data.width;
                    cutPicHeight = res.data.height;
                }
            })
    })
});
function upload_image_callback(ids, srcs, type, input_name = 'undefined')
{
    //如果是单图上传
    if (type == '1') {
        if (input_name != 'undefined') {
            var $input_file = $('.js-upload').find('input[name='+input_name+']');
        } else {
            var $input_file = $('.js-upload').find('input');
        }
    } else {
        if (input_name != 'undefined') {
            var $input_file = $('.js-uploads').find('input[name='+input_name+']');
        } else {
            var $input_file = $('.js-uploads').find('input');
        }
    }
    console.log($input_file, '$input_file');
    if (input_name != 'undefined') {
        var $input_file_name = input_name;
    } else {
        var $input_file_name = $input_file.attr('name');
    }
    // 是否多图片上传
    var $multiple = $input_file.data('multiple');
    console.log($input_file_name, '$input_file_name')
    // 图片列表
    var $file_list = $('#file_list_' + $input_file_name);

    for (var i = 0;i < ids.length;i++) {
        var $li = $(
            '<div id="' + ids[i] + '" class="file-item js-gallery thumbnail">' +
            '<a data-magnify="gallery" id="iview"><img src="'+srcs[i]+'" style="width:100px;height:100px"></a>' +
            '<div class="info">' + srcs[i] + '</div>' +
            '<i class="fa fa-times-circle remove-picture"></i>' +
            ($multiple ? '<i class="fa fa-fw fa-arrows move-picture"></i>' : '') +
            '<div class="progress progress-mini remove-margin active" style="display: none">' +
            '<div class="progress-bar progress-bar-primary progress-bar-striped" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div>' +
            '</div>' +
            '</div>'
            ),
            $img = $li.find('img');

        if ($multiple) {
            $file_list.append($li);
        } else {
            $file_list.html($li);
            $input_file.val('');
        }
        $img.attr('src', srcs[i]);
        if ($multiple) {
            if ($input_file.val()) {
                $input_file.val($input_file.val() + ',' + ids[i]);
            } else {
                $input_file.val(ids[i]);
            }
            $li.find('.remove-picture').attr('data-id', ids[i]);
        } else {
            $input_file.val(ids[i]);
        }
        $li.find('img').attr('data-original', srcs[i]);
        $li.find('#iview').attr('href', srcs[i]);
        // 删除图片
        $file_list.delegate('.remove-picture', 'click', function() {
            $(this).closest('.file-item').remove();
            if ($multiple) {
                var ids = [];
                $file_list.find('.remove-picture').each(function() {
                    ids.push($(this).data('id'));
                });
                $input_file.val(ids.join(','));
            } else {
                $input_file.val('');
            }
            Stars.iview();
        });
    }

}